<?php


use Illuminate\Support\Facades\Storage;

define('HEARTBEAT_TIME', 25);

if(!function_exists('formatResponse')){

    /**
     * 格式化响应数据
     *
     * @param   string|int      $errCode
     * @param   string          $message
     * @param   mixed           $data
     * @return  array
     */
    function formatResponse($errCode = 0, $message = null, $data = null){

        $response = [
            'status' => [
                'errCode' => $errCode,
                'message' => $message
            ],
        ];
        

        if(!is_null($data)){
            array_set($response, 'data', $data); 
        }

        return $response;
    }
}

if(!function_exists('formatJsonResponse')){

    /**
     * 格式化响应数据
     *
     * @param   mixed           $data
     * @param   string          $message
     * @param   string|int      $errCode
	 * @return  \Illuminate\Http\JsonResponse
     */
    function formatJsonResponse($data = null, $message = '正常', $errCode = 0){

        
        
        return Response::json(formatResponse($errCode, $message, $data));
    }
}

if(!function_exists('randomNumber')){
    function randomNumber($billType){
        
        $billNumberModel = app(\App\Models\BillSystemnumber::class);

        $billNumber = $billNumberModel->where('bill_type',$billType)->first();

        if($billNumber->current_day == date('Ymd')){
            $systemNumber = $billNumber->system_number;

            $billNumber->system_number = cover($billNumber->system_number+1);

            $billNumber->save();

            return $billNumber->bill_type.$billNumber->current_day.$systemNumber;
        }else{
            $systemNumber = cover(1);

            $billNumber->current_day = date('Ymd');

            $billNumber->system_number = cover($systemNumber+1);

            $billNumber->save();

            return $billNumber->bill_type.$billNumber->current_day.$systemNumber;
        }

        dd($billNumber);

        return 'JSJL'.date('Ymd').redisNumber();
    }

    function cover($number){
        $coverNumber = 5;

        $tmp = '';

        for ($i=strlen($number); $i < $coverNumber; $i++) { 
            $tmp .= '0';
        }

        return $tmp.$number;
    }
}

if(!function_exists('itemOption')){
    function itemOption(Array $array){
        $temp = [];
        $i = 0;
        foreach($array as $key => $value){
            $temp[$i]['key'] = $key;
            $temp[$i]['value'] =$value;
            $i++;
        }

        return $temp;
    }
}

if(!function_exists('isDebugging')){

    /**
     * 检测是否调试模式
     *
     * @return bool
     */
    function isDebugging(){
        
        return Config::get('app.debug'); 
    }
}

if (!function_exists('filterToArray')) {
    function filterToArray($data,$key,$value)
    {       
        $array = [];
        foreach($data as $object)
        {   
            $array = array_add($array, $object->$key, $object->$value);
        }   
        return $array;
    }
}

if (!function_exists('uploadImage')) {
    function uploadImage($request, $fileID, $filedir)
    {
//        dd(storage_path("app/public/$filedir"));
        if ($request->hasFile($fileID) && ($file = $request->file($fileID))->isValid()) {
            $file->move(storage_path("app/public/$filedir"), $fileName = $file->hashName());
            return "/storage/$filedir/$fileName";
        } else {
            return null;
        }
    }
}

if (!function_exists('changeImage')) {
    function changeImage($request, $fileID, $filedir, $oldFilePath)
    {
        if ($request->hasFile($fileID) && ($file = $request->file($fileID))->isValid()) {
            $name = trim(strrchr($oldFilePath, '/'), '/');
            Storage::disk('local')->delete("/public/$filedir/$name");
            $file->move(storage_path("app/public/$filedir"), $fileName = $file->hashName());
            return "/storage/$filedir/$fileName";
        } else {
            return null;
        }
    }
}

if (!function_exists('deleteImage')) {
    function deleteImage($filePath)
    {
        $arr = explode('/', $filePath);
        $filedir = $arr[2];
        $name = $arr[3];

        if (Storage::disk('local')->delete("/public/$filedir/$name")) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('http_requests')) {
    /**
     * CURL 模块
     * @param  string $uri      目的地址
     * @param  string $postData POST数组
     * @param  string $cookie   携带Cookie
     * @param  string|array $header   自定义Header
     * @param  bool $header_on 是否显示返回头
     * @param  string $referer 设置Header中referer值
     * @param  string $userpassword 设置用户登录账号密码（格式xxx:xxx）
     * @return string
     */
    function http_requests($uri, $postData = null, $cookie = null, $header = null, $header_on = false, $referer = null, $userpassword = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, $header_on);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if ($postData) { // post提交
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
        }

        if ($cookie) // 伪造cookie
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);

        if ($header) // 自定义header
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        if ($referer) // 设置header中referer
            curl_setopt($ch, CURLOPT_REFERER, $referer);

        if ($userpassword) // 设置用户名密码
            curl_setopt($ch, CURLOPT_USERPWD, $userpassword);

        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}